import { Component, Rect, UITransform, v3, Vec3, _decorator } from 'cc';
import { InputData } from '../../common/components/Joystick';

const { ccclass, property } = _decorator;

type Boundary = { left: number; right: number; top: number; bottom: number };

@ccclass('Player')
export default class Player extends Component {
	@property
	moveSpeed: number = 0;

	@property
	rotateSpeed: number = 0;

	@property
	minRotateAngle: number = 3;

	private _boundary: Boundary;
	private _inputData: InputData;
	private _updatedPosition: Vec3 = v3();
	private _uiTransform: UITransform;

	start() {
		this._updatedPosition.set(this.node.position.x, this.node.position.y);
		this._uiTransform = this.getComponent(UITransform);
	}

	public setPosition(position: Vec3) {
		this.node.setPosition(position);
		this._updatedPosition.set(this.node.position.x, this.node.position.y);
	}

	public setInput(input: InputData) {
		this._inputData = input;
	}

	public setBoundary(boundary: Rect) {
		this._boundary = {
			left: boundary.x - boundary.width * 0.5,
			right: boundary.x + boundary.width * 0.5,
			top: boundary.y + boundary.height * 0.5,
			bottom: boundary.y - boundary.height * 0.5
		};
	}

	update(dt: number) {
		if (this._inputData) {
			this._updatedPosition.x += this._inputData.direction.x * this.moveSpeed * dt;
			this._updatedPosition.y += this._inputData.direction.y * this.moveSpeed * dt;

			if (this._updatedPosition.x <= this._boundary.left + this._uiTransform.height * 0.5) {
				this._updatedPosition.x = this._boundary.left + this._uiTransform.height * 0.5;
			} else if (this._updatedPosition.x >= this._boundary.right - this._uiTransform.height * 0.5) {
				this._updatedPosition.x = this._boundary.right - this._uiTransform.height;
			}

			if (this._updatedPosition.y <= this._boundary.bottom + this._uiTransform.height * 0.5) {
				this._updatedPosition.y = this._boundary.bottom + this._uiTransform.height * 0.5;
			} else if (this._updatedPosition.y >= this._boundary.top - this._uiTransform.height * 0.5) {
				this._updatedPosition.y = this._boundary.top - this._uiTransform.height * 0.5;
			}

			this.node.setPosition(this._updatedPosition);

			const disAngle = (this._inputData.angle - this.node.angle) % 360;
			if (Math.abs(disAngle) > this.minRotateAngle) {
				// 旋转方向 ,走最短的方向
				const direction = Math.abs(disAngle) < 180 ? disAngle / Math.abs(disAngle) : -disAngle / Math.abs(disAngle);
				this.node.angle += direction * this.rotateSpeed * dt;
			}
		}
	}
}
